import core

import gdata.youtube.service
import difflib
import os
import sys
from mutagen.easyid3 import EasyID3

MAX_RESULTS_CHECKED = 10

class AvailabilityChecker():
	
	def __init__(self,yt_service):
		self.yt_service = yt_service

	def check_if_uploaded(self,artist,title):
		search_string = '"%s - %s"' % (artist,title)
		
		query = gdata.youtube.service.YouTubeVideoQuery()
		query.vq = search_string
		query.orderBy = 'relevance_lang_pl'
		query.max_results = MAX_RESULTS_CHECKED
		query.racy = 'exclude'
		query.category = 'music'
		query.strict = True
		feed = self.yt_service.YouTubeQuery(query)
		
		for entry in feed.entry:
			#print entry.title.text
			if self._match(artist,title,entry.title.text):
				return True
		
		return False
		
	def _match(self,artist,title,video_title):
		pattern = artist + title
		pattern = self._compact(pattern)
		
		feat_detected = False
		
		feat_strings = ("feat.","feat ","ft.","ft ")
		
		for feat_string in feat_strings:
			if feat_string in video_title.lower():
				feat_detected = True
				video_title_wo_feat = video_title[0 : video_title.lower().rindex(feat_string)]
				video_title_wo_feat = self._compact(video_title_wo_feat)
				break
		
		video_title = self._compact(video_title)
		
		if self._match_compacted(pattern,video_title):
			return True
		else:
			if feat_detected:
				return self._match_compacted(pattern,video_title_wo_feat)
			else:
				return False
	
	def _compact(self,str):
		str = self._strip_special_characters(str)
		str = str.lower()
		return str
	
	def _match_compacted(self,str1,str2):
		#print "comparing '%s' with '%s'" % (str1,str2)
		matcher = difflib.SequenceMatcher(None, str1, str2)
		ratio = matcher.ratio()
		return ratio > 0.9
		
	def _strip_special_characters(self,str):
		return ''.join(e for e in str if e.isalnum())
		
class FilesystemTracksMetadataIiterator():
	
	def __init__(self,dir_path):
		filepaths = [os.path.join(dir_path,filename) for filename in os.listdir(dir_path) if filename.endswith('.mp3')]
		if not filepaths:
			print "There are no mp3's in given folder"
			sys.exit(1)
		
		self.files_iter = iter(filepaths)
		
	def __iter__(self):
		return self
		
	def next(self):
		filepath = self.files_iter.next()
		
		audio = EasyID3(filepath)
		return audio['artist'][0], audio['title'][0]

def test():
	#authenticator = core.Authenticator('IAmPeteRockFan','ownage77')
	#yt_service = authenticator.create_authenticated_yt_service()
	yt_service = gdata.youtube.service.YouTubeService()
	checker = AvailabilityChecker(yt_service)

	#return checker.check_if_uploaded('Aim','Mag')

	not_uploaded_tracks = []

	iterator = FilesystemTracksMetadataIiterator('D:/Muzyka/Hip-hop instrumentale/Ametsub/The_Nothings_Of_The_North_(+_Full_CD_Vinyl_Artwork)')
	for artist,title in iterator:
		if not checker.check_if_uploaded(artist,title):
			track_name =  '%s - %s' % (artist,title)
			not_uploaded_tracks.append(track_name)
	
	if not_uploaded_tracks:
		print 'Tracks that are probably not uploaded:'
		for track in not_uploaded_tracks:
			print '* ' + track
	else:
		print 'Probably all tracks are already uploaded'
	